package com.mtk.launcher.activity;

import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.provider.Settings;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.cdl.library.listener.MoreButtonToggleListener;
import com.lark.wifi.util.MyLog;
import com.mtk.launcher.BuildConfig;
import com.mtk.launcher.databinding.ActivitySettingTimeBinding;
import com.mtk.launcher.util.DateAndTimeUtil;

import java.text.SimpleDateFormat;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import java.util.Set;

public class TimeAndDateActivity extends BaseActivity {


    ActivitySettingTimeBinding binding;

    private Calendar calendar;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivitySettingTimeBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        initView();
        initListener();
        // 初始化日历
        calendar = Calendar.getInstance();
    }

    private Handler handler = new Handler();

    @Override
    protected void onResume() {
        super.onResume();

        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                //延时获取数据，因为第一次可能取不到数据
                // 恢复设置状态
                restoreSettings();
                // 更新当前时间和日期显示
                updateDateTimeDisplay();
            }
        }, 300);
    }

    private void initView() {
        binding.included.title.setText("日期和时间");
    }

    private void initListener() {
        //使用网络提供的时间
        binding.switchButton.setOnMoretListener(new MoreButtonToggleListener() {
            @Override
            public void switchToggleView(View view, boolean isClick) {
                DateAndTimeUtil.setAutoTime(TimeAndDateActivity.this, isClick ? 1 : 0);
                updateDateTimeDisplay();
                updateManualOptionsVisibility(isClick);
            }
        });
        // 24小时制开关
        binding.switchButtonHourStyle.setOnMoretListener(new MoreButtonToggleListener() {
            @Override
            public void switchToggleView(View view, boolean isClick) {
                DateAndTimeUtil.set24Hour(TimeAndDateActivity.this, isClick);
                updateDateTimeDisplay();
            }
        });
        binding.included.llBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        // 手动设置日期
        binding.settingClickViewDate.setOnMoretListener(v -> showDatePickerDialog());

        // 手动设置时间
        binding.settingClickViewTime.setOnMoretListener(v -> showTimePickerDialog());

        // 手动设置时区
        binding.settingClickViewTimeZone.setOnMoretListener(v -> showTimeZonePickerDialog());
    }

    private void restoreSettings() {
        binding.switchButtonHourStyle.setSwitchStatues(DateAndTimeUtil.get24Hour(TimeAndDateActivity.this));
        boolean autoTimeEnabled = DateAndTimeUtil.getAutoTime(TimeAndDateActivity.this);
        MyLog.cdl("autoTimeEnabled=" + autoTimeEnabled);
        binding.switchButton.setSwitchStatues(autoTimeEnabled);
        String timeZero = getSystemTimeZone();
        binding.settingClickViewTimeZone.setTxtContent(timeZero);
        updateManualOptionsVisibility(autoTimeEnabled);
    }

    private void updateManualOptionsVisibility(boolean autoTimeEnabled) {
        binding.settingClickViewDate.setClickEnable(!autoTimeEnabled);
        binding.settingClickViewTime.setClickEnable(!autoTimeEnabled);
        binding.settingClickViewTimeZone.setClickEnable(!autoTimeEnabled);
    }

    private void updateDateTimeDisplay() {
        calendar = Calendar.getInstance();
        // 更新时间显示
        java.text.DateFormat timeFormat;
        boolean isUse24Hour = DateAndTimeUtil.get24Hour(TimeAndDateActivity.this);
        MyLog.e("updateDateTimeDisplay", "isUse24Hour:" + isUse24Hour);
        if (isUse24Hour) {
            timeFormat = new SimpleDateFormat("HH:mm", Locale.CHINA);
        } else {
            timeFormat = new SimpleDateFormat("hh:mm a", Locale.CHINA);
        }
        binding.settingClickViewTime.setTxtContent(timeFormat.format(calendar.getTime()));
        binding.switchButtonHourStyle.setTxtContent(timeFormat.format(calendar.getTime()));
        // 更新日期显示
        java.text.DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(this);
        binding.settingClickViewDate.setTxtContent(dateFormat.format(calendar.getTime()));
    }

    private void showTimePickerDialog() {
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int minute = calendar.get(Calendar.MINUTE);
        boolean isUse24Hour = DateAndTimeUtil.get24Hour(TimeAndDateActivity.this);
        TimePickerDialog timePickerDialog = new TimePickerDialog(
                this,
                (view, hourOfDay, minuteOfHour) -> {
                    calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
                    calendar.set(Calendar.MINUTE, minuteOfHour);
                    setSystemTime(calendar);
                    updateDateTimeDisplay();
                },
                hour,
                minute,
                isUse24Hour
        );
        timePickerDialog.show();
    }

    private void showDatePickerDialog() {
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);

        DatePickerDialog datePickerDialog = new DatePickerDialog(
                this,
                (view, yearSelected, monthOfYear, dayOfMonth) -> {
                    calendar.set(Calendar.YEAR, yearSelected);
                    calendar.set(Calendar.MONTH, monthOfYear);
                    calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                    setSystemTime(calendar);
                    updateDateTimeDisplay();
                },
                year,
                month,
                day
        );
        datePickerDialog.show();
    }

    private void showTimeZonePickerDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("选择时区");

        // 获取所有时区
        Set<String> timeZoneIds = ZoneId.getAvailableZoneIds();
        List<String> timeZoneList = new ArrayList<>();
        // 为列表添加一些常用时区
        addCommonTimeZones(timeZoneList);
        // 添加所有其他时区
        for (String id : timeZoneIds) {
            if (!timeZoneList.contains(id)) {
                timeZoneList.add(id);
            }
        }
        // 创建ListView
        ListView listView = new ListView(this);
        ArrayAdapter<String> adapter = new ArrayAdapter<>(
                this,
                android.R.layout.simple_list_item_1,
                timeZoneList
        );
        listView.setAdapter(adapter);

        builder.setView(listView);
        AlertDialog dialog = builder.create();

        listView.setOnItemClickListener((parent, view, position, id) -> {
            String selectedTimeZone = timeZoneList.get(position);
            binding.settingClickViewTimeZone.setTxtContent(selectedTimeZone);
            setSystemTimeZone(selectedTimeZone);
            dialog.dismiss();
        });
        dialog.show();
    }

    private void addCommonTimeZones(List<String> timeZoneList) {
        timeZoneList.add("Asia/Shanghai");
        timeZoneList.add("Asia/Tokyo");
        timeZoneList.add("Asia/Singapore");
        timeZoneList.add("Asia/Hong_Kong");
        timeZoneList.add("Asia/Seoul");
        timeZoneList.add("America/New_York");
        timeZoneList.add("America/Los_Angeles");
        timeZoneList.add("Europe/London");
        timeZoneList.add("Europe/Paris");
        timeZoneList.add("Australia/Sydney");
        timeZoneList.add("UTC");
    }

    private void setSystemTime(Calendar calendar) {
        boolean isUse24Hour = DateAndTimeUtil.get24Hour(TimeAndDateActivity.this);
        try {
            long when = calendar.getTimeInMillis();
            if (when / 1000 < Integer.MAX_VALUE) {
                Settings.System.putLong(getContentResolver(), Settings.System.TIME_12_24,
                        isUse24Hour ? 24 : 12);
                SystemClock.setCurrentTimeMillis(when);
                Toast.makeText(this, "时间已更新", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "设置时间失败，请确保已授予修改系统设置权限", Toast.LENGTH_SHORT).show();
        }
    }

    private void setSystemTimeZone(String timeZoneId) {
        if (BuildConfig.DEBUG) {
            return;
        }
        MyLog.cdl("setSystemTimeZone==" + timeZoneId);
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        alarmManager.setTimeZone(timeZoneId);
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                updateDateTimeDisplay();
            }
        }, 500);
    }

    private String getSystemTimeZone() {
        if (BuildConfig.DEBUG) {
            return "Asia/Shanghai";
        }
        ZoneId currentZone = ZoneId.systemDefault();
        MyLog.cdl("getSystemTimeZone==" + currentZone);
        return currentZone.getId();
    }


}
